<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="googlead9dc5c68da2c41a" />








  <meta name="baidu-site-verification" content="baV2kbPkNW" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico?v=5.1.4">


  <link rel="mask-icon" href="/images/favicon.ico?v=5.1.4" color="#222">





  <meta name="keywords" content="笔记,深度学习,神经网络,Coursera,吴恩达," />





  <link rel="alternate" href="/atom.xml" title="红色石头的机器学习之路" type="application/atom+xml" />






<meta name="keywords" content="笔记,深度学习,神经网络,Coursera,吴恩达">
<meta property="og:type" content="article">
<meta property="og:title" content="Coursera吴恩达《神经网络与深度学习》课程笔记（2）-- 神经网络基础之逻辑回归">
<meta property="og:url" content="https://redstonewill.github.io/2018/03/20/35/index.html">
<meta property="og:site_name" content="红色石头的机器学习之路">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://img.blog.csdn.net/20170926082756271?imageView/2/w/500/q/100">
<meta property="og:image" content="http://img.blog.csdn.net/20170926082756271?">
<meta property="og:image" content="http://img.blog.csdn.net/20170906231842576?">
<meta property="og:image" content="http://img.blog.csdn.net/20170926083044469?">
<meta property="og:image" content="http://img.blog.csdn.net/20170926083150863?">
<meta property="og:image" content="http://img.blog.csdn.net/20170926083227668?">
<meta property="og:image" content="http://img.blog.csdn.net/20170926083257736?">
<meta property="og:image" content="http://img.blog.csdn.net/20170926083336211?">
<meta property="og:updated_time" content="2018-03-20T12:18:40.344Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Coursera吴恩达《神经网络与深度学习》课程笔记（2）-- 神经网络基础之逻辑回归">
<meta name="twitter:image" content="http://img.blog.csdn.net/20170926082756271?imageView/2/w/500/q/100">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: 'ZFJHIGA2DV',
      apiKey: 'e3baeea7f059baffe169cc0eec8adacf',
      indexName: 'redstonewillblog',
      hits: {"per_page":10},
      labels: {"input_placeholder":"输入关键词进行搜索","hits_empty":"找不到关于 ${query} 的文章","hits_stats":"共找到 ${hits} 篇文章，耗时${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://redstonewill.github.io/2018/03/20/35/"/>





  <title>Coursera吴恩达《神经网络与深度学习》课程笔记（2）-- 神经网络基础之逻辑回归 | 红色石头的机器学习之路</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
	
	<a href="https://github.com/RedstoneWill" class="github-corner" aria-label="View source on Github"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
	
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">红色石头的机器学习之路</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">公众号ID：redstonewill</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-sitemap">
          <a href="/sitemap.xml" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br />
            
            站点地图
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  
  <div class="algolia-popup popup search-popup">
    <div class="algolia-search">
      <div class="algolia-search-input-icon">
        <i class="fa fa-search"></i>
      </div>
      <div class="algolia-search-input" id="algolia-search-input"></div>
    </div>

    <div class="algolia-results">
      <div id="algolia-stats"></div>
      <div id="algolia-hits"></div>
      <div id="algolia-pagination" class="algolia-pagination"></div>
    </div>

    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
  </div>




    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://redstonewill.github.io/2018/03/20/35/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="红色石头">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/blog-logo.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="红色石头的机器学习之路">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Coursera吴恩达《神经网络与深度学习》课程笔记（2）-- 神经网络基础之逻辑回归</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-03-20T20:06:57+08:00">
                2018-03-20
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/深度学习/" itemprop="url" rel="index">
                    <span itemprop="name">深度学习</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/深度学习/吴恩达神经网络与深度学习/" itemprop="url" rel="index">
                    <span itemprop="name">吴恩达神经网络与深度学习</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2018/03/20/35/" class="leancloud_visitors" data-flag-title="Coursera吴恩达《神经网络与深度学习》课程笔记（2）-- 神经网络基础之逻辑回归">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  4,002
                </span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="http://img.blog.csdn.net/20170926082756271?imageView/2/w/500/q/100" alt="这里写图片描述"><br><a id="more"></a></p>
<blockquote>
<p>我的CSDN博客地址：<a href="http://blog.csdn.net/red_stone1" target="_blank" rel="noopener">红色石头的专栏</a><br>我的知乎主页：<a href="https://www.zhihu.com/people/red_stone_wl" target="_blank" rel="noopener">红色石头</a><br>我的微博：<a href="https://weibo.com/6479023696/profile?topnav=1&amp;wvr=6&amp;is_all=1" target="_blank" rel="noopener">RedstoneWill的微博</a><br>我的GitHub：<a href="https://github.com/RedstoneWill" target="_blank" rel="noopener">RedstoneWill的GitHub</a><br>我的微信公众号：红色石头的机器学习之路（ID：redstonewill）<br>欢迎大家关注我！共同学习，共同进步！</p>
</blockquote>
<p>上节课我们主要对深度学习（Deep Learning）的概念做了简要的概述。我们先从房价预测的例子出发，建立了标准的神经网络（Neural Network）模型结构。然后从监督式学习入手，介绍了Standard NN，CNN和RNN三种不同的神经网络模型。接着介绍了两种不同类型的数据集：Structured Data和Unstructured Data。最后，我们解释了近些年来深度学习性能优于传统机器学习的原因，归结为三个因素：Data，Computation和Algorithms。本节课，我们将开始介绍神经网络的基础：逻辑回归（Logistic Regression）。通过对逻辑回归模型结构的分析，为我们后面学习神经网络模型打下基础。</p>
<h3 id="Binary-Classification"><a href="#Binary-Classification" class="headerlink" title="Binary Classification"></a>Binary Classification</h3><p>我们知道逻辑回归模型一般用来解决二分类（Binary Classification）问题。二分类就是输出y只有{0,1}两个离散值（也有{-1,1}的情况）。我们以一个图像识别问题为例，判断图片中是否有猫存在，0代表noncat，1代表cat。主要是通过这个例子简要介绍神经网络模型中一些标准化的、有效率的处理方法和notations。</p>
<p><img src="http://img.blog.csdn.net/20170926082756271?" alt="这里写图片描述"></p>
<p>如上图所示，这是一个典型的二分类问题。一般来说，彩色图片包含RGB三个通道。例如该cat图片的尺寸为（64，64，3）。在神经网络模型中，我们首先要将图片输入x（维度是（64，64，3））转化为一维的特征向量（feature vector）。方法是每个通道一行一行取，再连接起来。由于64x64x3=12288，则转化后的输入特征向量维度为（12288，1）。此特征向量x是列向量，维度一般记为$n_x$。</p>
<p>如果训练样本共有m张图片，那么整个训练样本X组成了矩阵，维度是（$n_x$，m）。注意，这里矩阵X的行$n_x$代表了每个样本$x^{(i)}$特征个数，列m代表了样本个数。这里，Andrew解释了X的维度之所以是（$n_x$，m）而不是（m，$n_x$）的原因是为了之后矩阵运算的方便。算是Andrew给我们的一个小小的经验吧。而所有训练样本的输出Y也组成了一维的行向量，写成矩阵的形式后，它的维度就是（1，m）。</p>
<h3 id="Logistic-Regression"><a href="#Logistic-Regression" class="headerlink" title="Logistic Regression"></a>Logistic Regression</h3><p>接下来我们就来介绍如何使用逻辑回归来解决二分类问题。逻辑回归中，预测值$\hat h=P(y=1\ |\ x)$表示为1的概率，取值范围在[0,1]之间。这是其与二分类模型不同的地方。使用线性模型，引入参数w和b。权重w的维度是（$n_x$，1），b是一个常数项。这样，逻辑回归的线性预测输出可以写成：</p>
<p>$$\hat y = w^Tx+b$$</p>
<p>值得注意的是，很多其它机器学习资料中，可能把常数b当做$w_0$处理，并引入$x_0=1$。这样从维度上来看，x和w都会增加一维。但在本课程中，为了简化计算和便于理解，Andrew建议还是使用上式这种形式将w和b分开比较好。</p>
<p>上式的线性输出区间为整个实数范围，而逻辑回归要求输出范围在[0,1]之间，所以还需要对上式的线性函数输出进行处理。方法是引入Sigmoid函数，让输出限定在[0,1]之间。这样，逻辑回归的预测输出就可以完整写成：</p>
<p>$$\hat y = Sigmoid(w^Tx+b)=\sigma(w^Tx+b)$$</p>
<p>Sigmoid函数是一种非线性的S型函数，输出被限定在[0,1]之间，通常被用在神经网络中当作激活函数（Activation function）使用。Sigmoid函数的表达式和曲线如下所示：</p>
<p>$$Sigmoid(z)=\frac{1}{1+e^{-z}}$$</p>
<p><img src="http://img.blog.csdn.net/20170906231842576?" alt="这里写图片描述"></p>
<p>从Sigmoid函数曲线可以看出，当z值很大时，函数值趋向于1；当z值很小时，函数值趋向于0。且当z=0时，函数值为0.5。还有一点值得注意的是，Sigmoid函数的一阶导数可以用其自身表示：</p>
<p>$$\sigma’(z)=\sigma(z)(1-\sigma(z))$$</p>
<p>这样，通过Sigmoid函数，就能够将逻辑回归的输出限定在[0,1]之间了。</p>
<h3 id="Logistic-Regression-Cost-Function"><a href="#Logistic-Regression-Cost-Function" class="headerlink" title="Logistic Regression Cost Function"></a>Logistic Regression Cost Function</h3><p>逻辑回归中，w和b都是未知参数，需要反复训练优化得到。因此，我们需要定义一个cost function，包含了参数w和b。通过优化cost function，当cost function取值最小时，得到对应的w和b。</p>
<p>提一下，对于m个训练样本，我们通常使用上标来表示对应的样本。例如$(x^{(i)},y^{(i)})$表示第i个样本。</p>
<p>如何定义所有m个样本的cost function呢？先从单个样本出发，我们希望该样本的预测值$\hat y$与真实值越相似越好。我们把单个样本的cost function用Loss function来表示，根据以往经验，如果使用平方错误（squared error）来衡量，如下所示：</p>
<p>$$L(\hat y,y)=\frac12(\hat y-y)^2$$</p>
<p>但是，对于逻辑回归，我们一般不使用平方错误来作为Loss function。原因是这种Loss function一般是non-convex的。non-convex函数在使用梯度下降算法时，容易得到局部最小值（local minumum），即局部最优化。而我们最优化的目标是计算得到全局最优化（Global optimization）。因此，我们一般选择的Loss function应该是convex的。</p>
<p>Loss function的原则和目的就是要衡量预测输出$\hat y$与真实样本输出y的接近程度。平方错误其实也可以，只是它是non-convex的，不利于使用梯度下降算法来进行全局优化。因此，我们可以构建另外一种Loss function，且是convex的，如下所示：</p>
<p>$$L(\hat y,y)=-(ylog\ \hat y+(1-y)log\ (1-\hat y))$$</p>
<p>我们来分析一下这个Loss function，它是衡量错误大小的，Loss function越小越好。</p>
<p>当y=1时，$L(\hat y,y)=-log\ \hat y$。如果$\hat y$越接近1，$L(\hat y,y)\approx 0$，表示预测效果越好；如果$\hat y$越接近0，$L(\hat y,y)\approx +\infty$，表示预测效果越差。这正是我们希望Loss function所实现的功能。</p>
<p>当y=0时，$L(\hat y,y)=-log\ (1-\hat y)$。如果$\hat y$越接近0，$L(\hat y,y)\approx 0$，表示预测效果越好；如果$\hat y$越接近1，$L(\hat y,y)\approx +\infty$，表示预测效果越差。这也正是我们希望Loss function所实现的功能。</p>
<p>因此，这个Loss function能够很好地反映预测输出$\hat y$与真实样本输出y的接近程度，越接近的话，其Loss function值越小。而且这个函数是convex的。上面我们只是简要地分析为什么要使用这个Loss function，后面的课程中，我们将详细推导该Loss function是如何得到的。并不是凭空捏造的哦。。。</p>
<p>还要提一点的是，上面介绍的Loss function是针对单个样本的。那对于m个样本，我们定义Cost function，Cost function是m个样本的Loss function的平均值，反映了m个样本的预测输出$\hat y$与真实样本输出y的平均接近程度。Cost function可表示为：</p>
<p>$$J(w,b)=\frac1m\sum_{i=1}^mL(\hat y^{(i)},y^{(i)})=-\frac1m\sum_{i=1}^m[y^{(i)}log\ \hat y^{(i)}+(1-y^{(i)})log\ (1-\hat y^{(i)})]$$</p>
<p>Cost function已经推导出来了，Cost function是关于待求系数w和b的函数。我们的目标就是迭代计算出最佳的w和b值，最小化Cost function，让Cost function尽可能地接近于零。</p>
<p>其实逻辑回归问题可以看成是一个简单的神经网络，只包含一个神经元。这也是我们这里先介绍逻辑回归的原因。</p>
<h3 id="Gradient-Descent"><a href="#Gradient-Descent" class="headerlink" title="Gradient Descent"></a>Gradient Descent</h3><p>我们已经掌握了Cost function的表达式，接下来将使用梯度下降（Gradient Descent）算法来计算出合适的w和b值，从而最小化m个训练样本的Cost function，即J(w,b)。</p>
<p>由于J(w,b)是convex function，梯度下降算法是先随机选择一组参数w和b值，然后每次迭代的过程中分别沿着w和b的梯度（偏导数）的反方向前进一小步，不断修正w和b。每次迭代更新w和b后，都能让J(w,b)更接近全局最小值。梯度下降的过程如下图所示。</p>
<p><img src="http://img.blog.csdn.net/20170926083044469?" alt="这里写图片描述"></p>
<p>梯度下降算法每次迭代更新，w和b的修正表达式为：</p>
<p>$$w:=w-\alpha\frac{\partial J(w,b)}{\partial w}$$</p>
<p>$$b:=b-\alpha\frac{\partial J(w,b)}{\partial b}$$</p>
<p>上式中，$\alpha$是学习因子（learning rate），表示梯度下降的步进长度。$\alpha$越大，w和b每次更新的“步伐”更大一些；$\alpha$越小，w和b每次更新的“步伐”更小一些。在程序代码中，我们通常使用dw来表示$\frac{\partial J(w,b)}{\partial w}$，用db来表示$\frac{\partial J(w,b)}{\partial b}$。微积分里，$\frac{df}{dx}$表示对单一变量求导数，$\frac{\partial f}{\partial x}$表示对多个变量中某个变量求偏导数。</p>
<p>梯度下降算法能够保证每次迭代w和b都能向着J(w,b)全局最小化的方向进行。其数学原理主要是运用泰勒一阶展开来证明的，可以参考我的另一篇博客中的Gradient Descent有提到如何推导：<a href="http://blog.csdn.net/red_stone1/article/details/72229903" target="_blank" rel="noopener">台湾大学林轩田机器学习基石课程学习笔记10 – Logistic Regression</a></p>
<h3 id="Derivatives"><a href="#Derivatives" class="headerlink" title="Derivatives"></a>Derivatives</h3><p>这一部分的内容非常简单，Andrew主要是给对微积分、求导数不太清楚的同学介绍的。梯度或者导数一定程度上可以看成是斜率。关于求导数的方法这里就不再赘述了。</p>
<h3 id="More-Derivative-Examples"><a href="#More-Derivative-Examples" class="headerlink" title="More Derivative Examples"></a>More Derivative Examples</h3><p>Andrew给出了更加复杂的求导数的例子，略。</p>
<h3 id="Computation-graph"><a href="#Computation-graph" class="headerlink" title="Computation graph"></a>Computation graph</h3><p>整个神经网络的训练过程实际上包含了两个过程：正向传播（Forward Propagation）和反向传播（Back Propagation）。正向传播是从输入到输出，由神经网络计算得到预测输出的过程；反向传播是从输出到输入，对参数w和b计算梯度的过程。下面，我们用计算图（Computation graph）的形式来理解这两个过程。</p>
<p>举个简单的例子，假如Cost function为J(a,b,c)=3(a+bc)，包含a，b，c三个变量。我们用u表示bc，v表示a+u，则J=3v。它的计算图可以写成如下图所示：</p>
<p><img src="http://img.blog.csdn.net/20170926083150863?" alt="这里写图片描述"></p>
<p>令a=5，b=3，c=2，则u=bc=6，v=a+u=11，J=3v=33。计算图中，这种从左到右，从输入到输出的过程就对应着神经网络或者逻辑回归中输入与权重经过运算计算得到Cost function的正向过程。</p>
<h3 id="Derivatives-with-a-Computation-Graph"><a href="#Derivatives-with-a-Computation-Graph" class="headerlink" title="Derivatives with a Computation Graph"></a>Derivatives with a Computation Graph</h3><p>上一部分介绍的是计算图的正向传播（Forward Propagation），下面我们来介绍其反向传播（Back Propagation），即计算输出对输入的偏导数。</p>
<p>还是上个计算图的例子，输入参数有3个，分别是a，b，c。</p>
<p>首先计算J对参数a的偏导数。从计算图上来看，从右到左，J是v的函数，v是a的函数。则利用求导技巧，可以得到：</p>
<p>$$\frac{\partial J}{\partial a}=\frac{\partial J}{\partial v}\cdot \frac{\partial v}{\partial a}=3\cdot 1=3$$</p>
<p>根据这种思想，然后计算J对参数b的偏导数。从计算图上来看，从右到左，J是v的函数，v是u的函数，u是b的函数。可以推导：</p>
<p>$$\frac{\partial J}{\partial b}=\frac{\partial J}{\partial v}\cdot \frac{\partial v}{\partial u}\cdot \frac{\partial u}{\partial b}=3\cdot 1\cdot c=3\cdot 1\cdot 2=6$$</p>
<p>最后计算J对参数c的偏导数。仍从计算图上来看，从右到左，J是v的函数，v是u的函数，u是c的函数。可以推导：</p>
<p>$$\frac{\partial J}{\partial c}=\frac{\partial J}{\partial v}\cdot \frac{\partial v}{\partial u}\cdot \frac{\partial u}{\partial c}=3\cdot 1\cdot b=3\cdot 1\cdot 3=9$$</p>
<p>为了统一格式，在程序代码中，我们使用da，db，dc来表示J对参数a，b，c的偏导数。</p>
<p><img src="http://img.blog.csdn.net/20170926083227668?" alt="这里写图片描述"></p>
<h3 id="Logistic-Regression-Gradient-Descent"><a href="#Logistic-Regression-Gradient-Descent" class="headerlink" title="Logistic Regression Gradient Descent"></a>Logistic Regression Gradient Descent</h3><p>现在，我们将对逻辑回归进行梯度计算。对单个样本而言，逻辑回归Loss function表达式如下：</p>
<p>$$z=w^Tx+b$$</p>
<p>$$\hat y=a=\sigma(z)$$</p>
<p>$$L(a,y)=-(ylog(a)+(1-y)log(1-a))$$</p>
<p>首先，该逻辑回归的正向传播过程非常简单。根据上述公式，例如输入样本x有两个特征$(x_1,x_2)$，相应的权重w维度也是2，即$(w_1,w_2)$。则$z=w_1x_1+w_2x_2+b$，最后的Loss function如下所示：</p>
<p><img src="http://img.blog.csdn.net/20170926083257736?" alt="这里写图片描述"></p>
<p>然后，计算该逻辑回归的反向传播过程，即由Loss function计算参数w和b的偏导数。推导过程如下：</p>
<p>$$da=\frac{\partial L}{\partial a}=-\frac ya+\frac{1-y}{1-a}$$</p>
<p>$$dz=\frac{\partial L}{\partial z}=\frac{\partial L}{\partial a}\cdot \frac{\partial a}{\partial z}=(-\frac ya+\frac{1-y}{1-a})\cdot a(1-a)=a-y$$</p>
<p>知道了dz之后，就可以直接对$w_1$，$w_2$和b进行求导了。</p>
<p>$$dw_1=\frac{\partial L}{\partial w_1}=\frac{\partial L}{\partial z}\cdot \frac{\partial z}{\partial w_1}=x_1\cdot dz=x_1(a-y)$$</p>
<p>$$dw_2=\frac{\partial L}{\partial w_2}=\frac{\partial L}{\partial z}\cdot \frac{\partial z}{\partial w_2}=x_2\cdot dz=x_2(a-y)$$</p>
<p>$$db=\frac{\partial L}{\partial b}=\frac{\partial L}{\partial z}\cdot \frac{\partial z}{\partial b}=1\cdot dz=a-y$$</p>
<p>则梯度下降算法可表示为：</p>
<p>$$w_1:=w_1-\alpha\ dw_1$$</p>
<p>$$w_2:=w_2-\alpha\ dw_2$$</p>
<p>$$b:=b-\alpha\ db$$</p>
<p><img src="http://img.blog.csdn.net/20170926083336211?" alt="这里写图片描述"></p>
<h3 id="Gradient-descent-on-m-examples"><a href="#Gradient-descent-on-m-examples" class="headerlink" title="Gradient descent on m examples"></a>Gradient descent on m examples</h3><p>上一部分讲的是对单个样本求偏导和梯度下降。如果有m个样本，其Cost function表达式如下：</p>
<p>$$z^{(i)}=w^Tx^{(i)}+b$$</p>
<p>$$\hat y^{(i)}=a^{(i)}=\sigma(z^{(i)})$$</p>
<p>$$J(w,b)=\frac1m\sum_{i=1}^mL(\hat y^{(i)},y^{(i)})=-\frac1m\sum_{i=1}^m[y^{(i)}log\ \hat y^{(i)}+(1-y^{(i)})log\ (1-\hat y^{(i)})]$$</p>
<p>Cost function关于w和b的偏导数可以写成和平均的形式：</p>
<p>$$dw_1=\frac1m\sum_{i=1}^mx_1^{(i)}(a^{(i)}-y^{(i)})$$</p>
<p>$$dw_2=\frac1m\sum_{i=1}^mx_2^{(i)}(a^{(i)}-y^{(i)})$$</p>
<p>$$db=\frac1m\sum_{i=1}^m(a^{(i)}-y^{(i)})$$</p>
<p>这样，每次迭代中w和b的梯度有m个训练样本计算平均值得到。其算法流程图如下所示：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">J=0; dw1=0; dw2=0; db=0;</span><br><span class="line">for i = 1 to m</span><br><span class="line">	z(i) = wx(i)+b;</span><br><span class="line">	a(i) = sigmoid(z(i));</span><br><span class="line">	J += -[y(i)log(a(i))+(1-y(i)）log(1-a(i));</span><br><span class="line">	dz(i) = a(i)-y(i);</span><br><span class="line">	dw1 += x1(i)dz(i);</span><br><span class="line">	dw2 += x2(i)dz(i);</span><br><span class="line">	db += dz(i);</span><br><span class="line">J /= m;</span><br><span class="line">dw1 /= m;</span><br><span class="line">dw2 /= m;</span><br><span class="line">db /= m;</span><br></pre></td></tr></table></figure>
<p>经过每次迭代后，根据梯度下降算法，w和b都进行更新：</p>
<p>$$w_1:=w_1-\alpha\ dw_1$$</p>
<p>$$w_2:=w_2-\alpha\ dw_2$$</p>
<p>$$b:=b-\alpha\ db$$</p>
<p>这样经过n次迭代后，整个梯度下降算法就完成了。</p>
<p>值得一提的是，在上述的梯度下降算法中，我们是利用for循环对每个样本进行dw1，dw2和db的累加计算最后再求平均数的。在深度学习中，样本数量m通常很大，使用for循环会让神经网络程序运行得很慢。所以，我们应该尽量避免使用for循环操作，而使用矩阵运算，能够大大提高程序运行速度。关于vectorization的内容我们放在下次笔记中再说。</p>
<h3 id="Summary"><a href="#Summary" class="headerlink" title="Summary"></a>Summary</h3><p>本节课的内容比较简单，主要介绍了神经网络的基础——逻辑回归。首先，我们介绍了二分类问题，以图片为例，将多维输入x转化为feature vector，输出y只有{0,1}两个离散值。接着，我们介绍了逻辑回归及其对应的Cost function形式。然后，我们介绍了梯度下降算法，并使用计算图的方式来讲述神经网络的正向传播和反向传播两个过程。最后，我们在逻辑回归中使用梯度下降算法，总结出最优化参数w和b的算法流程。</p>

      
    </div>
    
    
    
	
    
      <div>
        <div id="wechat_subscriber" style="display: block; padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/uploads/wechat-qcode.jpg" alt="红色石头 wechat" style="width: 200px; max-width: 100%;"/>
    <div>欢迎您扫一扫上面的微信公众号，了解更多AI资源！</div>
</div>

      </div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.png" alt="红色石头 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="红色石头 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    红色石头
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://redstonewill.github.io/2018/03/20/35/" title="Coursera吴恩达《神经网络与深度学习》课程笔记（2）-- 神经网络基础之逻辑回归">https://redstonewill.github.io/2018/03/20/35/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/笔记/" rel="tag"><i class="fa fa-tag"></i> 笔记</a>
          
            <a href="/tags/深度学习/" rel="tag"><i class="fa fa-tag"></i> 深度学习</a>
          
            <a href="/tags/神经网络/" rel="tag"><i class="fa fa-tag"></i> 神经网络</a>
          
            <a href="/tags/Coursera/" rel="tag"><i class="fa fa-tag"></i> Coursera</a>
          
            <a href="/tags/吴恩达/" rel="tag"><i class="fa fa-tag"></i> 吴恩达</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/03/19/34/" rel="next" title="Coursera吴恩达《神经网络与深度学习》课程笔记（1）-- 深度学习概述">
                <i class="fa fa-chevron-left"></i> Coursera吴恩达《神经网络与深度学习》课程笔记（1）-- 深度学习概述
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/03/22/36/" rel="prev" title="Coursera吴恩达《神经网络与深度学习》课程笔记（3）-- 神经网络基础之Python与向量化">
                Coursera吴恩达《神经网络与深度学习》课程笔记（3）-- 神经网络基础之Python与向量化 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- Go to www.addthis.com/dashboard to customize your tools -->
<div class="addthis_inline_share_toolbox">
  <script type = "text/javascript" src = "//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-5aaa217593e0eff1" async = "async" ></script>
</div>

      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zNDg0MS8xMTM3OA=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/blog-logo.jpg"
                alt="红色石头" />
            
              <p class="site-author-name" itemprop="name">红色石头</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">43</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/RedstoneWill" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="http://blog.csdn.net/red_stone1" target="_blank" title="CSDN">
                      
                        <i class="fa fa-fw fa-contao"></i>CSDN</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.zhihu.com/people/red_stone_wl/activities" target="_blank" title="知乎">
                      
                        <i class="fa fa-fw fa-globe"></i>知乎</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="http://weibo.com/redstonewill" target="_blank" title="微博">
                      
                        <i class="fa fa-fw fa-weibo"></i>微博</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:redstonewill@hotmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#Binary-Classification"><span class="nav-number">1.</span> <span class="nav-text">Binary Classification</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Logistic-Regression"><span class="nav-number">2.</span> <span class="nav-text">Logistic Regression</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Logistic-Regression-Cost-Function"><span class="nav-number">3.</span> <span class="nav-text">Logistic Regression Cost Function</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Gradient-Descent"><span class="nav-number">4.</span> <span class="nav-text">Gradient Descent</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Derivatives"><span class="nav-number">5.</span> <span class="nav-text">Derivatives</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#More-Derivative-Examples"><span class="nav-number">6.</span> <span class="nav-text">More Derivative Examples</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Computation-graph"><span class="nav-number">7.</span> <span class="nav-text">Computation graph</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Derivatives-with-a-Computation-Graph"><span class="nav-number">8.</span> <span class="nav-text">Derivatives with a Computation Graph</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Logistic-Regression-Gradient-Descent"><span class="nav-number">9.</span> <span class="nav-text">Logistic Regression Gradient Descent</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Gradient-descent-on-m-examples"><span class="nav-number">10.</span> <span class="nav-text">Gradient descent on m examples</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Summary"><span class="nav-number">11.</span> <span class="nav-text">Summary</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">红色石头</span>

  
</div>

<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_pv"></span>
</span>
</div>









<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共150.1k字</span>
</div>
        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  




  
  
  
  <link rel="stylesheet" href="/lib/algolia-instant-search/instantsearch.min.css">

  
  
  <script src="/lib/algolia-instant-search/instantsearch.min.js"></script>
  

  <script src="/js/src/algolia-search.js?v=5.1.4"></script>



  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("GPinP9RLLAEN4cQw3GyGH1i6-gzGzoHsz", "P23pTYCEXWROAMFxuaSGYGIa");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
